package com.utils.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

public class Io {
	/*
	 * 输入流复制到输出流
	 */
	public void copyFile(String fromFileName, String toFileName) {
		try {
			Writer write = new FileWriter(toFileName);
			InputStream ins = new FileInputStream(new File(fromFileName));
			IOUtils.copy(ins, write);
			// write.close();
			// ins.close();
			// 关闭输入流
			IOUtils.closeQuietly(write);
			IOUtils.closeQuietly(ins);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/*
	 * 复制文件
	 */
	public void copyFile(File fromFileName, File toFileName) {
		try {
			FileUtils.copyFile(fromFileName, toFileName);
			File destDir = new File("D:\\");
			// 文件复制到指定目录
			FileUtils.copyFileToDirectory(fromFileName, destDir);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/*
	 * 写文件 str 文本内容
	 */
	public void writeFile(String str) {
		try {
			File file = new File("c:\\name.txt");
			// 如果不存在，就新建一个，存在，就修改时间
			FileUtils.touch(file);
			FileUtils.writeStringToFile(file, str);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/*
	 * 将输入流转换成文本
	 */
	public String URLIoTest() {
		try {
			URL url = new URL("http://www.baidu.com");
			InputStream ins = url.openStream();
			String contents = IOUtils.toString(ins, "UTF-8");
			return contents;
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}

	/*
	 * 网络流保存为文件
	 */
	public void urlToFile() {
		try {
			URL url = new URL("http://www.163.com");
			File file = new File("c:\\163.html");
			FileUtils.copyURLToFile(url, file);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/*
	 * 文件目录操作
	 */
	public void DirOper() {
		try {
			File dir = new File("c:\\test");
			long size = FileUtils.sizeOfDirectory(dir);// 目录大小
			System.out.println(size);
			FileUtils.cleanDirectory(dir);// 清空目录下的文件
			FileUtils.deleteDirectory(dir);// 删除目录和目录下的文件
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
